#!/usr/bin/python

'''
Created on Mar 2, 2014

@author: Hovanes Egiyan
'''

import subsystem, mpod


def initDetectorMap():
    svtList= ['bot', 'top']
    for svtLabel in svtList :
        hybridDict = {}
        for hybrid in range(1, nHybrids+1  ):
            biasNumber = ( nHybrids * svtList.index(svtLabel) +  hybrid )
            crate = "svt"
            slot = biasNumber /  nSlotsPerBiasBoard
            channel =  biasNumber % nSlotsPerBiasBoard
            channelMap = { "crate":crate, "slot":slot, "channel":channel }
            hybridDict[hybrid] = channelMap
        CrSlChDict[svtLabel] = hybridDict           
    return

def initCrate():
#    crateInst = mpod.crate( "svt", "hvsvt3.jlab.org" )
    crateInst = mpod.crate( "B1:1:TOP", "halldmpod4.jlab.org" )
    crateInst.area = "B1"
    crateInst.rack = "1"
    crateInst.rocid = 1
    crateInst.location = "TOP"
    crateInst.AddBiasBoard( 0 )
    crateInst.AddBiasBoard( 1 )
    crateInst.AddBiasBoard( 2 )
    return crateInst



def openSQLFile():
    try :
        outFile = open( "svt_voltages.sql", "w")
    except IOError as err:
        raise err
  
    sql_string = 'CREATE TABLE Crate(crateid INTEGER PRIMARY KEY, name TEXT, area TEXT, rack INT, location TEXT, SN TEXT, Function TEXT, rocid INT, host TEXT, IP TEXT);\n'
    outFile.write(sql_string)
    sql_string = 'CREATE TABLE Module(moduleid INTEGER PRIMARY KEY, crateid INTEGER, slot INT, type TEXT, SN TEXT);\n'
    outFile.write(sql_string)
    sql_string = 'CREATE TABLE Channel(chanid INTEGER PRIMARY KEY, moduleid INTEGER, name TEXT, channel INT, system TEXT, col_name TEXT, enable INTEGER DEFAULT 1);\n'
    outFile.write(sql_string)
    sql_string = 'CREATE TABLE Detector_Hierarchy( id INTEGER PRIMARY KEY, parent_id INTEGER, name TEXT, type TEXT, chanid INTEGER, mtime DATETIME DEFAULT CURRENT_TIMESTAMP);\n'
    outFile.write(sql_string)
    
    outFile.write("\n\n\n") 
      
    return outFile

if __name__ == '__main__':
    CrSlChDict = {}
    nHybrids = 18
    nSlotsPerBiasBoard = 16

    print "Opening file"
    outFile = openSQLFile()
    
    mpodCrate = initCrate()
    mpodCrate.makeSQL(outFile)
    
    print "Initializing detector"
    initDetectorMap();
  
    print "Making SQL"
    # Make the SVT detector entry 
    svt = subsystem.subsystem( None, "Detector", "SVT" )  
    svt.makeSQL( outFile )
    # Make the bias subsystem entry
    bias = subsystem.subsystem( svt, "Voltage Type", "bias" )
    bias.makeSQL(outFile)
    
    # Loop over the layers of SVT and hybrids and make entries for the 
    # connection between the detector components and associated channels
    for svtLabel in CrSlChDict.keys() :
        hybridDict = CrSlChDict[svtLabel]
        svtSide = subsystem.subsystem( bias, "SVT Level", svtLabel )
        svtSide.makeSQL( outFile )
        for hybridNum in  hybridDict.keys():
            chanDict = hybridDict[hybridNum] 
            channid = mpodCrate.boardDict[chanDict["slot"]].channelMap[chanDict["channel"]].chanid
            hybrid = subsystem.subsystem( svtSide, "Hybrid",  str(hybridNum), channid )
            hybrid.makeSQL(outFile)
            # Make connections in the DB
#            mChan = mpod.mpodChannel( chanDict["crate"], chanDict["slot"], chanDict["channel"], "bias_chanid" )
            
            
            
